#!/bin/sh
# This regression test is a part of SIPp.
# Test abort-generated BYE uses dialog route set and remote target.
# Author: Daniel Donoghue
. "`dirname "$0"`/../functions"; init

## Phase 1: rrs-enabled dialog should drive BYE R-URI and Route.
sippbg -sf uas.xml -p 5070 -i 127.0.127.1 \
    -trace_msg -message_file uas_rrs.log >/dev/null 2>&1

# Control socket Q triggers abort-generated BYE.
(sleep 1; perl -e 'use IO::Socket::INET; my $s=IO::Socket::INET->new(PeerAddr=>"127.0.127.1",PeerPort=>8889,Proto=>"udp"); $s->send("Q");') &
ctrlpid=$!

sippfg -m 1 -sf uac.xml 127.0.127.1:5070 -i 127.0.127.1 -cp 8889 \
    -trace_msg -message_file uac_rrs.log -timeout 8 -timeout_error >/dev/null 2>&1
status=$?
wait $ctrlpid >/dev/null 2>&1

if test $status -gt 1; then
    fail "SIPp UAC job failed (rrs)"
elif test $status -eq 1; then
    echo "warning: SIPp UAC exited 1 (rrs)"
fi

bye_ruri=`tr -d '\r' < uas_rrs.log | sed -n '/^BYE /{s/^BYE //;s/ SIP\/2.0$//;p;q;}'`
bye_route=`sed -e '/^BYE /,/^$/!d;/^Route:/!d;s/[[:cntrl:]]//g' uas_rrs.log`

expected_ruri="sip:uas@127.0.127.1:5090;transport=udp"
expected_route="Route: <sip:127.0.127.1:5062;lr>, <sip:127.0.127.1:5061;lr>"

if test "x$bye_ruri" != "x$expected_ruri"; then
    fail "BYE R-URI unexpected, got: \"$bye_ruri\" (not \"$expected_ruri\")"
elif test "x$bye_route" != "x$expected_route"; then
    fail "BYE Route unexpected, got: \"$bye_route\" (not \"$expected_route\")"
fi

# Ensure background UAS from phase 1 is stopped before phase 2.
pkill -P$$
wait

## Phase 2: no-rrs should fall back to last Request-URI and no Route.
sippbg -sf uas_no_rrs.xml -p 5071 -i 127.0.127.1 \
    -trace_msg -message_file uas_norrs.log >/dev/null 2>&1

# Control socket Q triggers abort-generated BYE.
(sleep 1; perl -e 'use IO::Socket::INET; my $s=IO::Socket::INET->new(PeerAddr=>"127.0.127.1",PeerPort=>8890,Proto=>"udp"); $s->send("Q");') &
ctrlpid=$!

sippfg -m 1 -sf uac_no_rrs.xml 127.0.127.1:5071 -i 127.0.127.1 -cp 8890 \
    -trace_msg -message_file uac_norrs.log -timeout 8 -timeout_error >/dev/null 2>&1
status=$?
wait $ctrlpid >/dev/null 2>&1

if test $status -gt 1; then
    fail "SIPp UAC job failed (no-rrs)"
elif test $status -eq 1; then
    echo "warning: SIPp UAC exited 1 (no-rrs)"
fi

bye_ruri=`tr -d '\r' < uas_norrs.log | sed -n '/^BYE /{s/^BYE //;s/ SIP\/2.0$//;p;q;}'`
bye_route=`sed -e '/^BYE /,/^$/!d;/^Route:/!d;s/[[:cntrl:]]//g' uas_norrs.log`

expected_ruri="sip:service@127.0.127.1:5071"

if test "x$bye_ruri" != "x$expected_ruri"; then
    fail "BYE R-URI unexpected (no-rrs), got: \"$bye_ruri\" (not \"$expected_ruri\")"
elif test -n "$bye_route"; then
    fail "BYE Route unexpected (no-rrs), got: \"$bye_route\""
else
    ok
fi
